package com.cmcc.driver.ui.main.adapter

import android.content.Context
import android.os.Build
import android.os.CountDownTimer
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.cmcc.driver.R
import com.cmcc.driver.config.DriverPath
import com.cmcc.driver.data.entity.Order
import com.cmcc.driver.databinding.ListItemOrderInProgressBinding
import com.cmcc.shared.utils.TextViewUtil.setTextViewByLimit
import com.cmcc.shared.utils.TextViewUtil.setTextViewValue
import com.cmcc.shared.utils.TimeUtils
import com.cmcc.shared.utils.TimeUtils.getOverTimeGap
import com.cmcc.shared.utils.TimeUtils.getTimeGap
import com.cmcc.shared.utils.clickWithTrigger
import java.text.SimpleDateFormat
import java.util.*

class OrderInProgressAdapter() : RecyclerView.Adapter<OrderInProgressViewHolder>() {

    private var activity: FragmentActivity? = null
    private lateinit var context: Context
    private val countDownMap: SparseArray<CountDownTimer>? = SparseArray()

    private val currentList = mutableListOf<Order>()

    fun setActivity(activity: FragmentActivity?) {
        this.activity = activity
    }

    override fun getItemCount(): Int {
        return currentList.size
    }

    fun removeList() {
        currentList.clear()
    }

    fun addList(records: List<Order>) {
        currentList.addAll(records)
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OrderInProgressViewHolder {
        this.context = parent.context
        return OrderInProgressViewHolder(
            ListItemOrderInProgressBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }


    fun cancelTimers() {
        if (countDownMap == null) {
            return
        }
        for (i in 0 until countDownMap.size()) {
            val cdt = countDownMap.get(countDownMap.keyAt(i))
            cdt?.cancel()
        }
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onBindViewHolder(holder: OrderInProgressViewHolder, position: Int) {
        val model = currentList[position]
        val isOrderInProgress = isOrderInProgress(model.status,model.startTime ?: "")

        var countDownTimer: CountDownTimer? =
            countDownMap?.get(holder.binding.orderStatus.hashCode())
        countDownTimer?.cancel()

        if (isOrderInProgress) {
            if(model.type == 1){
                holder.binding.orderStatus.text = getTimeGap(context, model.createTime ?: "")

                countDownTimer = object : CountDownTimer(30 * 60 * 1000L, 1000L) {
                    override fun onTick(millisUntilFinished: Long) {
                        holder.binding.orderStatus.text = getTimeGap(context, model.createTime ?: "")
                    }

                    override fun onFinish() {

                    }
                }.start()
                countDownMap?.put(holder.binding.orderStatus.hashCode(), countDownTimer)
            }else{
                holder.binding.orderStatus.text = getOffTimeGap(context, model.startTime ?: "")

                countDownTimer = object : CountDownTimer(30 * 60 * 1000L, 1000L) {
                    override fun onTick(millisUntilFinished: Long) {
                        holder.binding.orderStatus.text = getOffTimeGap(context, model.startTime ?: "")
                    }

                    override fun onFinish() {

                    }
                }.start()
                countDownMap?.put(holder.binding.orderStatus.hashCode(), countDownTimer)
            }
        } else {
            holder.binding.orderStatus.text = getOverTimeGap(context, model.startTime ?: "")

            countDownTimer = object : CountDownTimer(60 * 60 * 1000L, 1000L) {
                override fun onTick(millisUntilFinished: Long) {
                    holder.binding.orderStatus.text = getOverTimeGap(context, model.startTime ?: "")
                }

                override fun onFinish() {

                }
            }.start()
            countDownMap?.put(holder.binding.orderStatus.hashCode(), countDownTimer)
        }



        setTextViewByLimit(
            holder.binding.orderType,
            model?.type == 1,
            context.getString(R.string.driver_real_time_order),
            context.getString(R.string.driver_reservation_order)
        )

        setTextViewByLimit(
            holder.binding.options.textView3,
            model?.type == 1,
            context.getString(R.string.time_real_time),
            context.getString(R.string.order_create_time, model?.startTime)
        )


        holder.binding.direction.directionStart.text = model.startAddress
        holder.binding.direction.directionEnd.text = model.endAddress

        setTextViewValue(
            context,
            holder.binding.options.tunnel,
            R.string.order_tunnel,
            model?.tunnel?.name,
            context.getString(R.string.what_ever)
        )


        setTextViewValue(
            context,
            holder.binding.options.tip,
            R.string.order_tip,
            model?.bountyFee,
            "0.00"
        )

        if(model.bountyFee==null){
            holder.binding.options.tip.text = context.resources.getString(R.string.driver_tip)+"HK\$ "+"0.00"
        }
        else{
            holder.binding.options.tip.text = context.resources.getString(R.string.driver_tip)+"HK\$ "+model.bountyFee.toString()+""
        }


        setTextViewValue(
            context,
            holder.binding.options.station,
            R.string.order_station,
            if (model?.stationIndex.isNullOrEmpty() || model?.stationIndex == "0") null else model?.stationIndex,
            if (model?.stationIndex.isNullOrEmpty() || model?.stationIndex == "0") context.getString(R.string.what_ever) else null
        )

        setTextViewValue(
            context,
            holder.binding.options.remarks,
            R.string.order_remark,
            model?.remark,
            context.getString(R.string.none)
        )

        setTextViewByLimit(
            holder.binding.receiveOrder,
            isOrderInProgress,
            context.getString(R.string.driver_order_in_progress),
            context.getString(R.string.driver_order_not_in_time)
        )

        //拒单finish()有返回的
        holder.binding.root.clickWithTrigger {
            ARouter.getInstance().build(DriverPath.ORDER_IN_PROGRESS_DETAIL)
                .withString("orderId", model.id).navigation(activity, 101)
        }
    }

    fun getOffTimeGap(context: Context, startTime: String): String {
        var format: SimpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        var startDate: Date = format.parse(startTime)

        var nowTime: Date = Date()
        var timeGap = startDate.time - nowTime.time
        return if (timeGap > 0) {
            TimeUtils.getOffTimeGap(context, startTime)
        } else {
            context.getString(com.cmcc.shared.R.string.book_time_come)
        }
    }

    private fun isOrderInProgress(status: Int, startTime: String): Boolean {
        if (status == 0 && !startTime.isNullOrEmpty()) {
            var format: SimpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            var startDate: Date = format.parse(startTime)

            var nowTime: Date = Date()
            var timeGap = startDate.time - nowTime.time
            if (timeGap > 0) {
                return false
            }
        }
        return true
    }


}

class OrderInProgressViewHolder(val binding: ListItemOrderInProgressBinding) :
    RecyclerView.ViewHolder(binding.root) {
    fun bind() {

    }
}